#!/bin/bash
set -e

arch="$(uname -m)"
unameOut="$(uname -s)"
case "${unameOut}" in
  Linux*)     platform=linux;;
  Darwin*)    platform=mac;;
  CYGWIN*)    platform=cygwin;;
  MINGW*)     platform=mingw;;
  *)          platform="UNKNOWN:${unameOut}"
esac

if [ "$platform" == "mac" ]; then
  echo "Detected MacOS"

  if ! command -v brew &> /dev/null; then
    /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
    eval "$(/opt/homebrew/bin/brew shellenv)"
  fi

  brew install \
    age \
    ava \
    cargo-watch \
    colima \
    docker \
    docker-compose \
    dotter \
    efm-langserver \
    ffmpeg \
    flameshot \
    fnm \
    fzf \
    gh \
    hyperfine \
    jq \
    just \
    keycastr \
    lazydocker \
    lnav \
    miniconda \
    node \
    pnpm \
    ripgrep \
    rustup \
    sops \
    tree \
    utm \
    vim \
    vlc \
    wezterm \
    wget \
    yq \
    zoxide \
    ;

  brew tap hashicorp/tap
  brew install hashicorp/tap/nomad
  if command -v rustup &> /dev/null; then
    rustup component add rust-src rust-analyzer
  fi

  brew install --cask nikitabobko/tap/aerospace

  if [[ "$(scutil --get ComputerName)" == *"Work"* ]]; then
    brew install \
      gettext \
      azure-data-studio \
      azure-cli \
      ;
  else
    brew install \
      betterzip \
      orbstack \
      ;
  fi
elif [ "$platform" == "linux" ]; then
  echo "Linux Detected"
  if [ -f "/etc/arch-release" ]; then
    echo "ArchLinux detected"

    if [ "$EUID" -eq 0 ]; then
      read -p "Enter non-root username: " USERNAME
      if id "$USERNAME" >/dev/null 2>&1; then
        echo 'user found'
      else
        useradd -m -G wheel "$USERNAME"
        passwd "$USERNAME"
      fi
      pacman -Sy sudo --noconfirm
      sed -i '/%wheel ALL=(ALL:ALL) ALL/s/^#//' /etc/sudoers
    else
      USERNAME=$(whoami)
    fi
    if ! command -v paru &> /dev/null; then
      sudo pacman -S --needed --noconfirm base-devel git
      sudo rm -rf /tmp/paru-bin
      sudo -u "$USERNAME" git clone https://aur.archlinux.org/paru-bin.git /tmp/paru-bin
      pushd /tmp/paru-bin
      sudo -u "$USERNAME" makepkg -si --noconfirm
      popd
      rm -rf /tmp/paru-bin
    fi
    sudo -u "$USERNAME" paru -Sy --noconfirm \
      age \
      miniconda3 \
      bspwm \
      curl \
      chromium \
      git \
      google-chrome \
      gvim \
      linux-headers \
      lua \
      picom \
      polybar \
      rofi \
      sxhkd \
      unzip \
      wezterm \
      xsel
    if [[ $arch != "aarch64" ]]; then
      sudo -u "$USERNAME" paru -Sy --noconfirm \
        dotter-rs-bin
    fi
    sudo -u "$USERNAME" paru -Sy --noconfirm xorg xfce4 sddm
    sudo -u "$USERNAME" systemctl enable sddm
  else
    echo "Unsupported Linux Distro"
    exit 1
  fi
fi
